package encrypt

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"

	"gitee.com/wdxtub/gocdt/file"
)

// 用于 aes 加密的工具函数
func aesPadding(src []byte, blockSize int) []byte {
	padnum := blockSize - len(src)%blockSize
	pad := bytes.Repeat([]byte{byte(padnum)}, padnum)
	return append(src, pad...)
}

// 用于 aes 加密的工具函数
func aesUnpadding(src []byte) []byte {
	n := len(src)
	unpadnum := int(src[n-1])
	return src[:n-unpadnum]
}

// AESEncrypt AES 加密
func AESEncrypt(src []byte, aesKeyPath string) ([]byte, error) {
	//打开文件
	key, err := file.ReadFileContent(aesKeyPath)
	if err != nil {
		return nil, err
	}
	block, _ := aes.NewCipher(key)
	src = aesPadding(src, block.BlockSize())
	blockmode := cipher.NewCBCEncrypter(block, key)
	blockmode.CryptBlocks(src, src)
	return src, nil
}

// AESDecrypt AES 解密
func AESDecrypt(src []byte, aesKeyPath string) ([]byte, error) {
	//打开文件
	key, err := file.ReadFileContent(aesKeyPath)
	if err != nil {
		return nil, err
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockmode := cipher.NewCBCDecrypter(block, key)
	blockmode.CryptBlocks(src, src)
	src = aesUnpadding(src)
	return src, nil
}
